﻿using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;

namespace MagicButtonApp
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private static readonly HttpClient client = new HttpClient();

        // 用于存储 IP 地址的属性
        public string PublicIpAddress
        {
            get { return (string)GetValue(PublicIpAddressProperty); }
            set { SetValue(PublicIpAddressProperty, value); }
        }

        public static readonly DependencyProperty PublicIpAddressProperty =
            DependencyProperty.Register("PublicIpAddress", typeof(string), typeof(MainWindow), new PropertyMetadata(""));

        // 用于存储完整响应报文的属性
        public string ResponseBody
        {
            get { return (string)GetValue(ResponseBodyProperty); }
            set { SetValue(ResponseBodyProperty, value); }
        }

        public static readonly DependencyProperty ResponseBodyProperty =
            DependencyProperty.Register("ResponseBody", typeof(string), typeof(MainWindow), new PropertyMetadata(""));

        public MainWindow()
        {
            InitializeComponent();
            // 设置 DataContext 为当前的 Window 实例
            DataContext = this;
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string ipAddress = await GetPublicIpAddressAsync();
                PublicIpAddress = string.IsNullOrEmpty(ipAddress) ? "未能获取到 IP 地址。" : $"请求者的 IP 地址是: {ipAddress}";
            }
            catch (Exception ex)
            {
                PublicIpAddress = $"发生错误: {ex.Message}";
                ResponseBody = ""; // 清空响应报文
            }
        }

        private async Task<string> GetPublicIpAddressAsync()
        {
            try
            {
                // 使用一个提供 IP 地址查询服务的 API
                HttpResponseMessage response = await client.GetAsync("https://api.ipify.org?format=json");
                response.EnsureSuccessStatusCode(); // 抛出状态码异常以指示失败。
                string responseBody = await response.Content.ReadAsStringAsync();

                // 将完整响应报文赋值给属性
                ResponseBody = $"完整响应报文:\n{responseBody}";

                // 解析 JSON 响应
                using (JsonDocument document = JsonDocument.Parse(responseBody))
                {
                    if (document.RootElement.TryGetProperty("ip", out JsonElement ipElement))
                    {
                        return ipElement.GetString();
                    }
                }
                return null;
            }
            catch (HttpRequestException e)
            {
                ResponseBody = $"HTTP 请求错误:\n{e.Message}";
                return null;
            }
            catch (JsonException e)
            {
                ResponseBody = $"JSON 解析错误:\n{e.Message}";
                return null;
            }
            catch (Exception e)
            {
                ResponseBody = $"其他错误:\n{e.Message}";
                return null;
            }
        }
    }
}